<template>
  <view>
    <uv-navbar title="" placeholder bgColor="transparent" leftIcon="" :autoBack="true">
      <template #left>
        <view class="order_notice_status_icon">
          <image src="/static/images/detail_back_common.png" style="width: 22px;height: 9px;"></image>
        </view>
      </template>
      <template #center> 磅单明细 </template>
    </uv-navbar>

    <view class="data_detail">
      <view class="data_detail_content">
        <view class="data_detail" v-for="item in schemas" :key="item.key">
          <view>{{ item.label }}</view>
          <view>{{ form[item.field] }}</view>
        </view>
      </view>
      <view class="" style="height: 100px;">

      </view>
    </view>

    <view class="bottom_btns">
      <view class="btns_content">
        <view class="btn btns_left" @click="goChangeData()">
          修改数据
        </view>
        <view class="btn btns_right" @tap="previewImage">
          查看图片
        </view>
      </view>
    </view>
  </view>

</template>

<script lang="ts" setup>
import dayjs from 'dayjs'
import { ref, reactive, toRaw, unref } from 'vue'
import { usePoundStore } from '@/stores'
import { onReady } from '@dcloudio/uni-app'
import { TableNameEnum, CURDOperationEnum } from '@/enums/tableCurdEnum'
import mqttStatus, { tableCurd, execCmd, cmdKey } from '@/utils/mqtt';

const poundStore = usePoundStore()

const saving = ref(false)

const pickerIns = ref()
const picker = reactive({
  show: false,
  columns: [],
  defaultIndex: [],
  current: null,
})

const datePickerIns = ref()
const datePicker = reactive({
  show: false,
  current: null,
  value: '',
  mode: 'date'
})

const editMode = ref(false)


const formIns = ref()


const form = ref({

})

const rules = reactive({

})

const schemas = ref([])

const formItemHandleMaps = [
  {
    fields: [
      'Kh',
      'Ch',
      'Wz',
      'Mzsby',
      'Pzsby',
      'ICCard',
      'By',
      'WeighName',
      'Weigh2Name',
      'AxleNum',
      'GoodsSpec',
      'Fhdw',
      'Shdw',
      'Driver',
      'DriverPhone',
    ],
    component: 'Input',
    rulesHandle: (rawField) => {
      if (rawField.key === 'Ch') {
        return [
          {
            required: true,
            trigger: 'blur',
            message: '该项必填',
          },
        ];
      }
      return [];
    },
  },
  {
    fields: ['Mz', 'Pz', 'Jz', 'Kz', 'Sz', 'Bz', 'WeighingTimes', 'Je', 'GoodsPrice'],
    component: 'InputNumber',
  },
  {
    fields: ['Mzrq', 'Pzrq', 'Jzrq', 'EntryTime'],
    component: 'DatePicker',
    rulesHandle: (rawField) => {
      if (rawField.key === 'Mzrq') {
        return [
          {
            required: true,
            trigger: ['blur', 'change'],
            message: '该项必填',
          },
        ];
      }
      return [];
    },
    componentPropsHandle: (rawField) => {
      return {
        showTime: true,
      };
    },
    defaultValueHandle: (rawField) => {
      return dayjs(new Date()).format('YYYY-MM-DD HH:mm:ss');
    },
  },
  {
    fields: ['IsFinish', 'Valid'],
    component: 'RadioGroup',
    componentPropsHandle: (rawField) => {
      return {

        options: rawField.children.map((p) => {
          return {
            label: p.label,
            value: p.value ? true : false,
          };
        }),
      };
    },
    defaultValueHandle: (rawField) => {
      return true;
    },
    rulesHandle: (rawField) => {
      return [
        {
          field: rawField.key,
          trigger: ['change'],
          required: true,
          message: '该项必选',
          type: 'boolean',
        },
      ];
    },
  },
  {
    fields: ['Gblx'],
    component: 'Select',
    componentPropsHandle: (rawField) => {
      return {
        options: rawField.children,
        style: 'width: "100%"',
      };
    },
    defaultValueHandle: (rawField) => {
      return rawField.children[0]?.value;
    },
    itemPropsHandle: (rawField) => {
      return {
        style: 'width: "100%"',
      };
    },
  },
];

const goChangeData = () => {
  uni.navigateTo({
    url: `change?id=${form.value.AutoNo}`,
    events: {
      'updated': (data) => {
        form.value = data
        eventChannel.emit('updated')
      }
    },
    success: ({ eventChannel }) => {
      eventChannel.emit('init', { ...toRaw(unref(form.value)) })
    },
  })
}

const datePickerCancel = () => {

}
const datePickerConfirm = (e) => {
  form.value[datePicker.current.field] = dayjs(e.value).format('YYYY-MM-DD HH:mm:ss')
}
const showDatePicker = (item) => {
  if (!editMode.value) {
    return
  }
  uni.hideKeyboard()
  datePicker.mode = item.componentProps && item.componentProps.showTime ? 'datetime' : 'date'
  datePicker.current = item
  datePicker.value = form.value[item.field]
  datePickerIns.value.open()
}
const pickerCancel = () => {

}
const pickerConfirm = (e) => {
  form.value[picker.current.field] = e.value[0]
}
const showPicker = (item) => {
  if (!editMode.value) {
    return
  }
  uni.hideKeyboard()
  const array = item.componentProps.options.map(p => p.label)
  const curVal = form.value[item.field]
  picker.current = item
  picker.columns = [array]
  picker.defaultIndex = [array.findIndex(p => p == curVal)]
  pickerIns.value.open()
}


let eventChannel = null

onReady(() => {
  const pages = getCurrentPages();
  const page = pages[pages.length - 1];

  eventChannel = page.getOpenerEventChannel()
  eventChannel.on('init', (data) => {
    schemas.value = poundStore.state.fields
      .filter((p) => !['By20'].includes(p.key))
      .map((p) => {
        let component = 'Input';
        let componentProps = {};
        let defaultValue = undefined;
        let itemProps = {};
        let rules = [];
        if (p.key.indexOf('By') === -1 && p.key.indexOf('Kh') === -1) {
          const item = formItemHandleMaps.find((s) => s.fields.includes(p.key));
          if (item) {
            component = item.component;
            if (item.componentPropsHandle) {
              componentProps = item.componentPropsHandle(p);
            }
            if (item.defaultValueHandle) {

              defaultValue = item.defaultValueHandle(p);
            }
            if (item.itemPropsHandle) {
              itemProps = item.itemPropsHandle(p);
            }
            if (item.rulesHandle) {
              rules = item.rulesHandle(p);
            }
          }
        }

        return {
          field: p.key,
          label: p.value,
          component: component,
          componentProps,
          defaultValue,
          itemProps,
          rules,
        };
      });
    form.value = data
  })
})

const previewImage = () => {
  if (!mqttStatus.online) {
    uni.showToast({
      title: '站点主程序未上线或已断开',
      icon: 'none'
    })
    return
  }
  uni.showLoading({
    title: '处理中,请稍后...',
    mask: true
  })
  execCmd(
    cmdKey.poundImage,
    [form.value.Bh, form.value.Ch],
    ({ Success, Message, Body }) => {
      if (!Success) {
        uni.showToast({
          title: Message,
          icon: 'none'
        })
        return;
      }
      const { images } = Body;
      if (images.length === 0) {
        uni.showToast({
          title: '该磅单暂无图片',
          icon: 'none'
        })
        return;
      }
      uni.hideLoading()
      uni.previewImage({
        current: 0,
        urls: images
      })
    },
    true,
  );
}

const toggleEditMode = () => {
  editMode.value = !editMode.value
}

const submit = () => {
  if (!mqttStatus.online) {
    uni.showToast({
      title: '站点主程序未上线或已断开',
      icon: 'none'
    })
    return
  }
  formIns.value.validate().then(() => {
    saving.value = true
    uni.showLoading({
      title: '正在保存...',
      mask: true
    })

    tableCurd(
      {
        tableName: TableNameEnum.WeighingRecord,
        operation: CURDOperationEnum.Save,
        body: { ...form.value }, // 非批量数据,  直接传记录数据即可
      },
      ({ Success, Message }) => {
        if (!Success) {
          saving.value = false;
          uni.showToast({
            title: `操作失败:${Message}`,
            icon: 'none'
          })
          return;
        }
        uni.showToast({
          title: `${form.value.Bh} 保存成功`,
          icon: 'none'
        })
        eventChannel.emit('updated')
        setTimeout(() => {
          uni.navigateBack()
        }, 1500)
        saving.value = false;
      },
    );


  }).catch(() => { })
}

</script>

<style scoped lang="scss">
@import "@/styles/aj_custom/index.scss";

.data_detail {
  background-color: white;
  margin: 5px 10px;
  border-radius: 10px;

  .data_detail_content {
    padding: 5px 10px;

    .data_detail {
      display: flex;
      justify-content: space-between;
      border-radius: 0px;
      border-bottom: 1px solid rgb(210 206 206 / 50%);
      padding: 10px 5px;
    }
  }
}

.bottom_btns {
  position: fixed;
  bottom: 0;
  right: 0;
  width: 100%;

  .btns_content {
    display: flex;
    justify-content: space-between;
    margin: 10px 20px;

    .btn {
      border-radius: 25px;
      text-align: center;
      padding: 5px 25px;
    }

    .btns_left {
      border: 1px solid blue;
    }

    .btns_right {
      color: white;
      background-color: blue;
    }
  }
}
</style>
